Create controls at runtime -II



In this snippet/article we will learn how to react to events occuring in controls created at runtime. For Ex How do we react to a click event of a command button which was created at runtime. .We will use a technique called as Subclassing to do this. Before we start doing this make sure you have read/viewed the earlier snippet/article on how to create the controls from here.

Put the following declarations in a .bas module

Public Declare Function SetWindowLong Lib "user32.dll" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nindex As Long, ByVal dwnewlong As Long) As Long

Public Declare Function CallWindowProc Lib "user32.dll" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, lParam As Long) As Long

Public Const WM_LBUTTONDOWN = &H201
Public Const WM_LBUTTONUP = &H202
Public Const GWL_WNDPROC = (-4)
Global oldWndProc As Long

The Functions SetWindowLong and CallWindowProc are used to subclass the control.

Put the following piece of code in the same event as that in which you are creating the control i.e .If you are creating the control in the form load event then put the following piece of code in that event.

oldWndProc = SetWindowLong(cmdInput.hWnd, GWL_WNDPROC, AddressOf newWndProc)

Here cmdInput is the command button which was created at runtime,newWndProc is the function which is going to handle the messages/events .

Next we write the public function in a .bas module which would process all the messages/events of the control.

Here is the function

Public Function newWndProc(ByVal hWnd As Long, ByVal uMsg As Long, ByVal wParam As Long, lParam As Long) As Long
If uMsg = WM_LBUTTONDOWN Then
Form1.Text1.Text = "ok"
End If
newWndProc = CallWindowProc(oldWndProc, hWnd, uMsg, wParam, lParam)
End Function

What this function does is when the command button is clicked it prints "ok" into the textbox on form1.

You can modify the message i.e WM_LBUTTONDOWN to any suitable message that you wish to intercept.

Download a simple Demo application from here

Questions/Comments send them to venky@venkydude.com.